package com.huluobo.a2203kotlindouyindemo.video

import android.content.Intent
import android.util.Log
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.view.animation.AnimationUtils
import android.widget.EditText
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2203kotlindouyindemo.R
import com.huluobo.a2203kotlindouyindemo.adapter.CommentAdapter
import com.huluobo.a2203kotlindouyindemo.adapter.MultiVideoAdapter
import com.huluobo.a2203kotlindouyindemo.adapter.VIdeoAdapter
import com.huluobo.a2203kotlindouyindemo.databinding.FragmentVideoBinding
import com.huluobo.a2203kotlindouyindemo.live.LiveActivity
import com.huluobo.a2203kotlindouyindemo.login.LoginActivity
import com.huluobo.base.bean.CommentBean
import com.huluobo.base.bean.VideoBean
import com.huluobo.base.db.AppDBUtils
import com.huluobo.base.net.Const
import com.huluobo.base.view.BaseMVVMFragment
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.umeng.socialize.ShareAction
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb

class VideoFragment : BaseMVVMFragment<FragmentVideoBinding, VideoViewModel>() {
    private lateinit var videoAdapter: MultiVideoAdapter

    //    private val videoList = mutableListOf<VideoBean>()
    private var currentPosition = 0
    private lateinit var player: StandardGSYVideoPlayer
    private lateinit var commentAdapter: CommentAdapter
    private val commentList = mutableListOf<CommentBean>()
    override fun getLayoutId(): Int = R.layout.fragment_video

    override fun initData() {
        viewModel.getVideoList(1, 20)

        viewModel.getVideoListSuccess.observe(this) {
            if (it.code == 200) {
//                videoList.clear()
//                videoList.addAll(it.data)
                videoAdapter.data.clear()
                videoAdapter.data.addAll(it.data)
                videoAdapter.notifyDataSetChanged()
            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.getVideoListFailed.observe(this) {
            Log.i("TagA", "获取视频列表失败:$it")
        }

        viewModel.likeVideoSuccess.observe(this) {
            ToastUtils.showLong(it.message)
            if (it.code == 200) {
                videoAdapter.data[currentPosition].dianzan = 1
                videoAdapter.notifyItemChanged(currentPosition)
            }
        }

        viewModel.likeVideoFailed.observe(this) {
            Log.i("TagA", "点赞失败:$it")
        }

        viewModel.noLikeVideoSuccess.observe(this) {
            ToastUtils.showLong(it.message)
            if (it.code == 200) {
                videoAdapter.data[currentPosition].dianzan = 0
                videoAdapter.notifyItemChanged(currentPosition)
            }
        }

        viewModel.noLikeVideoFailed.observe(this) {
            Log.i("TagA", "取消点赞失败:$it")
        }

        viewModel.followAuthSuccess.observe(this) {
            ToastUtils.showLong(it.message)
            if (it.code == 200) {
                videoAdapter.data[currentPosition].guanzhu = 1
                videoAdapter.notifyItemChanged(currentPosition)
            }
        }

        viewModel.followAuthFailed.observe(this) {
            Log.i("TagA", "关注失败:$it")
        }

        viewModel.getCommentListSuccess.observe(this) {
            if (it.code == 200) {
                commentList.clear()
                commentList.addAll(it.data)
                commentAdapter.notifyDataSetChanged()
            } else {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.getCommentListFailed.observe(this) {
            Log.i("TagA", "获取评论列表失败")
        }

        viewModel.sendCommentSuccess.observe(this) {
            ToastUtils.showLong(it.message)
            if (it.code == 200) {
                commentAdapter.data.addAll(0, it.data)
                commentAdapter.notifyDataSetChanged()

                val editText =
                    videoAdapter.getViewByPosition(currentPosition, R.id.item_video_comment_input_et) as EditText
                editText.text.clear()
            }
        }
    }

    override fun initView() {
        val linearLayoutManager = LinearLayoutManager(requireContext())
        dataBinding.videoRv.layoutManager = linearLayoutManager
        val pagerSnapHelper = PagerSnapHelper()
        pagerSnapHelper.attachToRecyclerView(dataBinding.videoRv)
        videoAdapter = MultiVideoAdapter()
        dataBinding.videoRv.adapter = videoAdapter

        dataBinding.videoRv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                currentPosition = linearLayoutManager.findFirstVisibleItemPosition()

                player =
                    videoAdapter.getViewByPosition(currentPosition, R.id.item_video_gsyPlayer) as StandardGSYVideoPlayer

//                player.startPlayLogic()
            }
        })

        videoAdapter.addChildClickViewIds(
            R.id.item_video_like_iv,
            R.id.item_video_add_iv,
            R.id.item_video_comment_iv,
            R.id.item_video_close_iv,
            R.id.item_video_comment_send_iv,
            R.id.item_video_follow_iv,
            R.id.item_video_share_iv,
            R.id.item_video_full_cl,
            R.id.item_video_live_cl
        )

        videoAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (SPUtils.getInstance().getString(Const.PARAM_TOKEN).isEmpty()) {
                val intent = Intent(requireContext(), LoginActivity::class.java)
                startActivity(intent)
            } else {
                val videoBean = adapter.data[position] as VideoBean
                when (view.id) {
                    R.id.item_video_like_iv -> likeVideo(videoBean)
                    R.id.item_video_add_iv -> followAuth(videoBean)
                    R.id.item_video_comment_iv -> openComment(videoBean)
                    R.id.item_video_close_iv -> closeComment()
                    R.id.item_video_comment_send_iv -> sendComment(videoBean)
                    R.id.item_video_follow_iv -> followVideo(videoBean)
                    R.id.item_video_share_iv -> shareVideo(videoBean)
                    R.id.item_video_full_cl -> fullScreen()
                    R.id.item_video_live_cl -> toLiveRoom(videoBean)
                }
            }
        }
    }

    private fun toLiveRoom(videoBean: VideoBean) {
        val intent = Intent(requireContext(), LiveActivity::class.java)
        intent.putExtra("videoBean", videoBean)
        startActivity(intent)
    }

    private fun fullScreen() {
        player.isRotateViewAuto = true
        player.startWindowFullscreen(requireContext(), false, false)
    }

    private fun shareVideo(videoBean: VideoBean) {
        val umImage = UMImage(requireContext(), videoBean.videomainimg)//生成一个分享的缩略图
        umImage.compressStyle = UMImage.CompressStyle.SCALE//设置图片压缩

        val umWeb = UMWeb(videoBean.videopath)
        umWeb.title = videoBean.authname//设置分享标题
        umWeb.setThumb(umImage)//设置分享图片
        umWeb.description = videoBean.caption

        ShareAction(requireActivity())
            .withMedia(umWeb)
            .open()
    }

    private fun followVideo(videoBean: VideoBean) {
        AppDBUtils.getDb().getVideoDao().insertVideo(videoBean)
    }

    private fun sendComment(videoBean: VideoBean) {
        val editText = videoAdapter.getViewByPosition(currentPosition, R.id.item_video_comment_input_et) as EditText
        val sendMessage = editText.text.toString()
        if (sendMessage.isNotEmpty()) {
            viewModel.sendComment(sendMessage, videoBean.id)
        } else {
            ToastUtils.showLong("请输入评论内容")
        }
    }

    private fun closeComment() {
        val commentLayout = videoAdapter.getViewByPosition(currentPosition, R.id.item_video_comment_ll)
        if (commentLayout != null) {
            commentLayout.visibility = View.GONE
            val animOut = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_out)
            animOut.duration = 500
            animOut.setAnimationListener(object : AnimationListener {
                override fun onAnimationStart(animation: Animation?) {
                }

                override fun onAnimationEnd(animation: Animation?) {
                    commentLayout.visibility = View.GONE
                    dataBinding.videoRv.setIntercept(true)
                }

                override fun onAnimationRepeat(animation: Animation?) {
                }
            })
            commentLayout.startAnimation(animOut)
        }
    }

    private fun openComment(videoBean: VideoBean) {
        dataBinding.videoRv.setIntercept(false)
        val commentLayout = videoAdapter.getViewByPosition(currentPosition, R.id.item_video_comment_ll)
        if (commentLayout != null) {
            commentLayout.visibility = View.VISIBLE
            val animIn = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_in)
            animIn.duration = 500
            animIn.setAnimationListener(object : AnimationListener {
                override fun onAnimationStart(animation: Animation?) {
                    viewModel.getCommentList(videoBean.id)
                }

                override fun onAnimationEnd(animation: Animation?) {
                }

                override fun onAnimationRepeat(animation: Animation?) {
                }
            })
            commentLayout.startAnimation(animIn)

            val commentRv: RecyclerView =
                videoAdapter.getViewByPosition(currentPosition, R.id.item_video_comment_rv) as RecyclerView
            commentRv.layoutManager = LinearLayoutManager(requireContext())
            commentAdapter = CommentAdapter(commentList)
            commentRv.adapter = commentAdapter
        }
    }

    private fun followAuth(videoBean: VideoBean) {
        viewModel.followAuth(videoBean.authname)
    }

    private fun likeVideo(videoBean: VideoBean) {
        if (videoBean.dianzan == 0) {
            viewModel.likeVideo(videoBean.id)
        } else {
            viewModel.noLikeVideo(videoBean.id)
        }
    }

    override fun getViewModel(): Class<VideoViewModel> = VideoViewModel::class.java
}